<?php


namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Finance\Wallet;
use App\Models\Finance\WalletLog;
use App\Models\Goods\Product;
use App\Models\Goods\ProductDiscount;
use App\Models\Goods\ProductPower;
use App\Models\Goods\UserProduct;
use App\Models\Goods\UserProductPower;
use App\Models\Partner\Partner;
use App\Models\Partner\PartnerUser;
use App\Models\Partner\UserProductPartner;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class GoodsController extends Controller
{

    protected $product;

    protected $productDiscount;

    private $pledge;

    public function __construct()
    {
        parent::__construct();
        /*$this->product = new Product();
        $this->productDiscount = new ProductDiscount();
        $pledgeShow = $this->redis->exists('pledge');
        if($pledgeShow){
            $this->pledge = json_decode($this->redis->get("pledge"));
        }else{
            $pledgeStr = file_get_contents("https://api2.filscout.com/api/v2/network/overview");
            $this->pledge = json_decode($pledgeStr);
            $this->redis->set("pledge",$pledgeStr,60);
        }*/

    }

    public function index(Request $request){

        $page = $this->decryptData($request->post('page'));
        $tt = $this->decryptData($request->post('tt'));
        //$coin = $this->decryptData($request->post('coin'));
        $page = ($page - 1) * 10;
        $sql = "select
                p.id,
                p.title,
                p.summary,
                p.period_of_validity,
                p.per_phs,
                pd.type,
                pd.discount_price,
                pd.limit,
                pd.end_time,
                pd.start_time,
                p.user_id,
                p.status,
                pd.sell_status,
                p.price,
                p.product_day,
                p.pay_coin,
                p.dig_coin,
                p.tech_fee,
                p.phs_wei
                from
                    yida_products p
                left join yida_product_discounts pd on p.id = pd.product_id
                where p.status = 1
                and p.tt = {$tt}
                order by p.user_id desc,pd.product_id desc,p.weight desc
                limit {$page},10";

        $countSql = "select
                    count(p.id) num
                from
                    yida_products p
                left join yida_product_discounts pd on p.id = pd.product_id
                where p.status = 1
                and p.tt = {$tt}
                order by p.user_id desc,pd.product_id desc,p.weight desc";

        $count = DB::select($countSql);
        $model = DB::select($sql);
        $model = array_map('get_object_vars',$model);

        foreach ($model as $key=>$value) {
            if ($value['summary']) {
                $model[$key]['summary'] = array_column(array_map("get_object_vars", json_decode($value['summary'])), 'key');
            }
            $model[$key]['discount_price'] = $value['sell_status'] == 1 ? 0 : $value['discount_price'];
            $model[$key]['limit'] = $value['sell_status'] == 1 ? 0 : $value['limit'];
            $model[$key]['end_time'] = $value['sell_status'] == 1 ? 0 : $value['end_time'];
            $model[$key]['start_time'] = $value['sell_status'] == 1 ? 0 : $value['start_time'];

            $day=$value['product_day'];
            $model[$key]['product_day_str'] = $day;
            if($value['user_id']){
                $model[$key]['user_id'] = array_column(json_decode($value['user_id']),'key');
            }
            if(is_null($value['type'])){
                $model[$key]['type'] = 0;
            }

        }
        if ($model) {
            return $this->ajaxSuccess(['model' => $model, 'total' => $count[0]->num]);
        } else {
            return $this->ajaxSuccess([]);
        }

    }



    public function detail(Request $request){

        $id = $this->decryptData($request->post('id'));
        $model = Product::with('discount')->where('id',$id)->first();
        if(isset($model->discount->sell_status) && $model->discount->sell_status == 1) {
            return $this->ajaxError('該活動已售完！');
        }

        if($model->discount)
        {
            if(!empty($model->discount->title))$model->title=$model->discount->title;
            $model['discount']['start_time']=  $model->discount->start_time ? date('Y-m-d H:i:s',strtotime($model['discount']['start_time'])) : null;
            $model['discount']['end_time']  =  $model->discount->end_time ? date('Y-m-d H:i:s',strtotime($model['discount']['end_time'])) : null;

        }

        $model->this_day=date("Y-m-d");
        $productDay=0;
        if($model->product_day >0) {
            $day=$model->product_day;
            $productDay=$day;
            $model->product_date = date("Y-m-d", strtotime("+".$day." day"));
        }else{
            $model->product_date="待定";
        }
        $day=181;
        if($model->period_of_validity > 0)$day=$model->period_of_validity;
        if($productDay > 0)$day=$day+$productDay;
        $model->last_date=date("Y-m-d",strtotime("+$day day"));

        $rs = $model->toArray();

        $rs['consume'] =$model->consume."kw/h";
        $rs['share_img_str'] = env('APP_URL').'/uploads/'.$model->images;

        $rs['summary'] = !empty($model->summary) ? array_column(json_decode($model->summary),'key') : $model->summary;
        $rs['user_id'] = !empty($model->user_id) ? array_column(json_decode($model->user_id),'key') : $model->user_id;
        $goodsPower = ProductPower::where('product_id',$id)->first();
        $rs['once_consume'] = isset($goodsPower->once_consume) ? $goodsPower->once_consume : 0;
        $rs['unit_price'] = isset($goodsPower->unit_price) ? $goodsPower->unit_price : 0;
        $rs['month'] = isset($goodsPower->month) ? $goodsPower->month : 1;
        if($rs){
            return  $this->ajaxSuccess($rs);
        }else{
            return $this->ajaxSuccess([]);
        }

    }




    public function goodsPurchase(Request $request){

        $data = $this->decryptData($request->post());
        $current_user = $this->userInfo();


        $model = Product::with('discount')->where('status',1)->where('id',$data['id'])->first();
        if(empty($model)){
            return $this->ajaxError('请从新选择');
        }
        // $model->price=$model->price_str;
        //$model->custody_fee = $model->custody_fee_str;
        $num   = intval($this->decryptData($request->post('num',0)));
        if( $num < 0 ) {
            return $this->ajaxError('購買份額不能小於1');
        }
        if($model->total_phs < $model->per_phs * $num && $model->total_phs != -1){
            return $this->ajaxError('此商品算力已售完');
        }


        if ($model->discount) {
            $time=time();
            if($model->discount->type == ProductDiscount::TYPE_DISCOUNT ){
                if(strtotime($model->discount->start_time) > $time){
                    return $this->ajaxError('活動未開始，不可購買');
                }
                if(strtotime($model->discount->end_time) < $time && !empty($model->discount->end_time)){
                    return $this->ajaxError('活動已結束，不可購買');
                }
            }
            //限量如果设为已售完则卖不了
            if($model->discount->type == ProductDiscount::TYPE_LIMIT){
                if($model->discount->sell_status == 1 || $model->discount->limit <= 0){
                    return $this->ajaxError('該活動已售完！');
                }
            }
            if(!empty($model->discount->title))$model->title=$model->discount->title;
            if ($model->discount->type == ProductDiscount::TYPE_NEW) {
                $isOld = UserProduct::where('user_id', $current_user->id)
                    ->value('id');
                if ($isOld) {
                    return $this->ajaxError('新用戶才可以下單哦~');
                }
            }

            $model->price = $model->discount->discount_price;

            $count = UserProduct::where('user_id', $current_user->id)
                ->where('discounts_id',$model->discount->id)
                ->where('status',UserProduct::STATUS_PAYED)
                ->count();
            if ($model->discount->frequency > 0 && $count > $model->discount->frequency) {
                return $this->ajaxError('購買次數已超出限製哦~');
            }
        }

        DB::beginTransaction();
        try {

            $amount = bcmul($model->price,$num,8);
            $order_sn = UserProduct::gen_order_sn($current_user->id,$model->id);
            $user_product = new UserProduct();

            $totalPhs=bcmul($model->per_phs,$num,2);

            $user_product->user_id = $current_user->id;
            $user_product->product_id = $model->id;
            $user_product->dig_coin= $model->dig_coin;
            $user_product->order_sn      = $order_sn ;
            $user_product->product_title = $model->title;
            $user_product->buy_shares    = $num;
            $user_product->buy_price     = $model->price;
            $user_product->amount        = $amount;
            $user_product->pay_coin      = $model->pay_coin;
            $user_product->tt 			 = intval($model->tt);
            $user_product->total_phs     = $totalPhs;
            $user_product->expires_at    = time() + 900;
            $user_product->status        = UserProduct::STATUS_UNPAY;
            $user_product->custody_fee   = $model->custody_fee;
            $user_product->tech_fee      = $model->tech_fee ;
            $user_product->discounts_id  = $model->discount->id ?? 0;
            $user_product->produce_at = strtotime(date("Y-m-d",strtotime("+$model->product_day day")));
            $user_product->product_expires_at = strtotime(date("Y-m-d",strtotime("+$model->product_day day")))
                + ($model->period_of_validity * 60 * 60 *24);
            $user_product->phs_ratio=$model->phs_ratio;
            $user_product->pay_type = $model->pay_coin == "FIL" ?  3 : 1;
            $user_product->save();

            if(!empty($power)){
                $return = $this->powerTime($data['month'],$user_product->produce_at);
                $orderPower = new UserProductPower();
                $orderPower->order_id = $user_product->id;
                $orderPower->month = $return['month'];
                $orderPower->day = $return['day'];
                $orderPower->produce_at = $user_product->produce_at;
                $orderPower->product_expires_at = $return['last_time'];
                $orderPower->money = $power->unit_price * $power->once_consume * 24 * ($return['month'] * 30 + $return['day']) * $num;
                $orderPower->save();
            }
            if ($model->discount && $model->discount->type == ProductDiscount::TYPE_LIMIT) {
                $cha=$model->discount->limit - $num;
                if($cha < 0)$cha=0;
                ProductDiscount::where('id',$model->discount->id)->update(['limit' =>$cha ]);
            }

            if($model->total_phs > 0){
                $model->decrement('total_phs',$model->per_phs * $num);
            }

            DB::commit();
            return $this->ajaxSuccess($user_product->toArray());


        }catch (\Exception $e){
            DB::rollBack();
            return $this->ajaxError($e->getMessage());

        }catch (\PDOException $e){
            DB::rollBack();
            return $this->ajaxError($e->getMessage());
        }

    }




    public function orderDetail(Request $request){

        $id = $this->decryptData($request->post('id'));
        $orderPower = UserProductPower::where('order_id',$id)->first();
        $model = UserProduct::where('id',$id)->first();
        $model->amount += isset($orderPower->money) ? $orderPower->money : 0;
        if(empty($model)){
            return $this->ajaxError('該訂單沒找到');
        }
        if($model){
            return $this->ajaxSuccess($model->toArray());
        }else{
            return  $this->ajaxError();
        }

    }



    public function payOrder(Request $request){

        $id = $this->decryptData($request->post('id'));
        $type = $this->decryptData($request->post('type')) ?? 1;
        $secondaryPassword = $this->decryptData($request->post('secondary_password'));
        $order = UserProduct::where('id',$id)->first();

        if( empty($order) || $order->status != UserProduct::STATUS_UNPAY) {
            return  $this->ajaxError('該訂單當前不可支付');
        }

        $current_user = $this->userInfo();

        if(!password_verify($secondaryPassword,$current_user->secondary_password)){
            return $this->ajaxError('交易密碼錯誤');
        }

        DB::beginTransaction();

        try {

            $orderPower = UserProductPower::where('order_id',$id)->value('money');
            $money = isset($orderPower) ? $orderPower : 0;
            $amount = $order->amount;
            $wallet = Wallet::where('user_id',$current_user->id)->where('coin',$coin)->first();

            $beforeAmount = $wallet->balance_available;
            if ($wallet->balance_available - ($amount+$money) < 0) {
                return  $this->ajaxError('有效余額不足');
            }
            $wallet->decrement('balance_available', $amount+$money);
            $walletLog = new WalletLog();
            $walletLog->user_id = $current_user->id;
            $walletLog->amount = $amount;
            $walletLog->date = date("Y-m-d");
            $walletLog->test = "商品购买";
            $walletLog->amount_type = 2;
            $walletLog->ip = $request->ip();
            $walletLog->coin = $coin;
            $walletLog->status = 1;
            $walletLog->type = 4;
            $walletLog->order_id = $order->id;
            $walletLog->before_amount = $beforeAmount;
            $walletLog->after_amount = $beforeAmount - $amount;
            $walletLog->save();
            // 保存交易。

            $order->status = UserProduct::STATUS_PAYED;

            $order->pay_type = $type;
            $order->amount = $amount;
            $order->save();

            //分润逻辑搞定
            $this->PartnerUserEdition($current_user,$id);

            //支付电费
            $goodsPower = ProductPower::where('product_id',$order->product_id)->first();
            if($goodsPower){
                $this->PowerPay($order,$wallet,$money);
            }
            // 返回成功信息。
            DB::commit();
            return  $this->ajaxSuccess([]);
        }catch (\Exception $e){

            DB::rollBack();
            return $this->ajaxError($e->getMessage());

        }catch (\PDOException $e){

            DB::rollBack();
            return $this->ajaxError($e->getMessage());
        }

    }



    public function PowerPay($order,$wallet,$money){

        $beforeAmount = $wallet->balance_available;
        DB::beginTransaction();
        try {
            $orderPower = UserProductPower::where('order_id',$order->id)->first();
            $orderPower->status = 2;
            $orderPower->save();
            $walletLog = new WalletLog();
            $walletLog->user_id = $order->user_id;
            $walletLog->amount = $orderPower->money;
            $walletLog->date = date("Y-m-d");
            $walletLog->test = "電費繳納";
            $walletLog->amount_type = 2;
            $walletLog->ip = request()->ip();
            $walletLog->coin = "USDT";
            $walletLog->status = 1;
            $walletLog->type = 8;
            $walletLog->order_id = $order->id;
            $walletLog->fee = 0;
            $walletLog->before_amount = $beforeAmount + $money;
            $walletLog->after_amount = $beforeAmount;
            $walletLog->save();
            DB::commit();

        }catch (\Exception $e){

            DB::rollBack();
            return $this->ajaxError($e->getMessage());

        }catch (\PDOException $e){

            DB::rollBack();
            return $this->ajaxError($e->getMessage());
        }

    }








    public function orderList(Request $request){

        $status = $this->decryptData($request->post('status'));
        $page = $this->decryptData($request->post('page'));
        //$coin = $this->decryptData($request->post('coin'));
        $page = ($page - 1) * 10;
        $current_user = $this->userInfo();
        if($status){
            $where[] = ['status',$status];
        }
        $where[] = ['user_id',$current_user->id];
        $order = UserProduct::where("status",1)->select('id','expires_at','status')->get()->toArray();
        $time = time();
        foreach ($order as $value) {
            if ($value['expires_at'] <= $time) {
                UserProduct::where('id', $value['id'])->update(['status' => 4]);
            }
        }
        $model = UserProduct::with(['product'])->where($where)->orderBy('id','desc')
            ->get();
        $total = count($model);
        $model = $model->skip($page)->take(10)->toArray();
        foreach ($model as $key=>$value){
            $orderPower = UserProductPower::where('order_id',$value['id'])->first();
            $productExpiresAt = UserProductPower::where('order_id',$value['id'])->max('product_expires_at');
            $model[$key]['days'] = isset($orderPower->month) ? $orderPower->month * 30 + $orderPower->day : 0;
            $model[$key]['power_rate_amount'] = isset($orderPower->money) ? $orderPower->money : 0;
            $model[$key]['amount'] = $value['amount'] + $model[$key]['power_rate_amount'];
            $model[$key]['product_expires_at'] = !empty($productExpiresAt) ? date('Y-m-d',$productExpiresAt) : 0;
        }
        if($model){
            return $this->ajaxSuccess(['model'=>array_values($model),'total'=>$total]);
        }else{
            return $this->ajaxSuccess([]);
        }


    }


    public function extend(Request $request){

        $base64 = $request->post('extend');
        $id = $request->post('id');
        $order = UserProduct::where('id',$id)->first();
        $base_img = str_replace('data:image/jpg;base64,', '', $base64);
        //  设置文件路径和命名文件名称
        $path = 'extend/'.date("His",time())."_".rand(1111,9999).'.png';//名字
        //  创建将数据流文件写入我们创建的文件内容中
        $images = explode(',',$base_img);
        $image = base64_decode(@$images[1]);
        Storage::disk('public')->put($path,$image);
        // 输出文件
        $order->extend = $path;
        $order->save();
        return $this->ajaxSuccess([]);

    }

}
